package com.shunwang.tools.httpclientsupport.pool;

import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;

import com.shunwang.tools.httpclientsupport.exception.PoolConnectionException;
import com.shunwang.tools.httpclientsupport.exception.PoolException;

public abstract class Pool<T> {

	private final GenericObjectPool internalPool;
	
	public Pool(final GenericObjectPool.Config poolConfig,PoolableObjectFactory factory){
		this.internalPool = new GenericObjectPool(factory,poolConfig);
	}
	
	public T getResource(){
		try{
			return (T)this.internalPool.borrowObject();
		}catch(Throwable t){
			throw new PoolConnectionException("Could not get a resource form the pool",t);
		}
	}
	
	public void returnResource(final Object resource){
		try{
			this.internalPool.returnObject(resource);
		}catch(Throwable t){
			throw new PoolException("Could not return the resource to pool",t);
		}
	}
	
	public void returnBrokenResource(final T resource){
		try{
			this.internalPool.invalidateObject(resource);
		}catch(Throwable t){
			throw new PoolException("Could not validate the resource to pool",t);
		}
	}
	
	public void destory(){
		try{
			this.internalPool.close();
		}catch(Throwable t){
			throw new PoolConnectionException("Could not destory resource to the pool",t);
		}
	}
}
